<template>
	<view class="box">
		<view class="result" v-if="resultShow" @click.stop="resultShow=false">
			<view class="msgBox">{{alertMsg}}</view>
		</view>
		<view :style="[{animationDelay: '0.1s'}]" class="actItem">
			<view class="label">前置：</view>
			<view class="warnTbn" @click="actionCheck('checkStatus')">状态检测：{{nfcStatus=='1'?'初始':nfcStatus=='2'?'加密':'未检测'}}</view>
		</view>
		<view :style="[{animationDelay: '0.1s'}]" class="actItem">
			<view class="label">第一步：</view>
			<view class="warnTbn" @click="actionCheck('encode')">加密</view>
		</view>
		<view :style="[{animationDelay: '0.2s'}]" class="actItem">
			<view class="label">第二步：</view>
			<view class="warnTbn" @click="actionCheck('encodeCheck')">加密打卡</view>
		</view>
		<view :style="[{animationDelay: '0.3s'}]" class="actItem">
			<view class="label">第三步：</view>
			<view class="warnTbn" @click="actionCheck('decode')">还原</view>
		</view>
		<view :style="[{animationDelay: '0.4s'}]" class="actItem">
			<view class="label">第四步：</view>
			<view class="warnTbn" @click="actionCheck('decodeCheck')">还原打卡</view>
		</view>		
	</view>
</template>

<script>
	export default {
		name:'notask',
		data() {
			return {
				resultShow:false,
				alertMsg:'',//展示文字
				preStatus:'',//检测
				nfcActType:'',//要进行的操作  读还是写
				nfcStatusEncode:'',//操作 加密还是解密
				nfcStatus:'0',//状态 ，当前是加密还是解密0：未检测 1:初始  2：加密
				nfcClose:true,
				NFCAdapter:undefined,
				NFCType:undefined,
				action:'wait',// wait beforeSub  sub
				selected:'2',
				cardId:'',
				cardName:'',
				cardNo:'',
				remark:'',
				selectStatusFlag:false,
				status:'',
				cardWarn:true,//是否允许编辑
				picker: ['喵喵喵', '汪汪汪', '哼唧哼唧'],
				index:null,
				isWarn:false,//是否异常打卡
				pointList:[],//点位列表，异常时候可以手动选择
				pointName:'',
				pointId:'',
				pointIndex:-1,
			}
		},
		mounted() {
			 this.cloaseNfc();
			 // this.actionCheck('checkStatus');
		},
		methods: {
			cloaseNfc(){
				if(this.NFCAdapter){
					this.NFCAdapter.offDiscovered(this.discoverHandler)
					this.NFCAdapter.stopDiscovery()
					this.NFCAdapter = null
				}
			},
			actionCheck(hand){
				this.$tip.toast("请将设备放入识别区NFC")
				try{
					this.cloaseNfc();
				}catch(e){
					//TODO handle the exception
				}
				if(hand=='decode'){//还原
					this.preStatus = '2'
					this.nfcActType='edit'
					this.nfcStatusEncode='decode'
				}else if(hand=='encode'){//加密
					this.preStatus = '1'
					this.nfcActType='edit'
					this.nfcStatusEncode='encode'
				}else if(hand=='decodeCheck'){//还原打卡
					this.preStatus = '1'
					this.nfcActType='read'
					this.nfcStatusEncode='decode'
				}else if(hand=='encodeCheck'){//加密打卡
					this.preStatus = '2'
					this.nfcActType='read'
					this.nfcStatusEncode='encode'
				}else if(hand == 'checkStatus'){
					this.nfcActType='check'
				}
				this.NFCAdapter = wx.getNFCAdapter();
				this.NFClistener();	
			},
			NFClistener(){
				let _this = this;
				this.NFCAdapter.startDiscovery({
				  success: () => {
				    _this.$tip.alert("请将设备放入识别区NFC")
				    // 监听 NFC 标签
				    _this.NFCAdapter.onDiscovered(this.discoverHandler)
				  },
				  fail: error => {
					if(error.errMsg=='startDiscovery:fail:NFC discovery already started'){
						 _this.NFCAdapter.onDiscovered(this.discoverHandler)
					}
					_this.$tip.alert("请重试")
				    console.error(error)
				  }
				})
			},
			/**
			 * 监听回调
			 */
			discoverHandler(callback) {
				let _this = this;
			  console.log('==================== START ====================')
			  console.log('onDiscovered callback=>', callback)
			  const arr = [0x01, 0x01, 0x01, 0x01];
			  const writeBuffer = new Uint8Array(arr);
			  console.log('卡片的Idd',callback.id);  
			  console.log('卡片的Idd',new Uint8Array(callback.id).map(item=>'0x'+item.toString(16)));
			  
			  console.log(this.NFCType)
			  try{
				//   let cId = this.byteArrayToHexString(callback.id)
			 //    console.log('哦呦呦',cId)//4d45e29a
				// _this.cardNo = cId || ''
				// _this.action = 'sub';
				// _this.cloaseNfc();
				// _this.getCardInfo();
				// let bbbbb=[0x55,0x15,0x4c,0x85]
				let bbbbb=new Uint8Array(callback.id).map(item=>'0x'+item.toString(16))
				console.log('bbbb',bbbbb)
				this.NFCType = this.NFCAdapter.getMifareClassic();
				if(this.NFCType){
					 this.NFCType.connect({
					   success(res) {
						   console.log('连接成功了',_this.nfcStatus)
						   let arr = [0x60, _this.nfcActType=='read'?0x09:0x0b,...bbbbb, ...(_this.preStatus=='2'?[0x0b, 0x0b,0x0b, 0x0b, 0x0b, 0x0b]:[0xff, 0xff,0xff, 0xff, 0xff, 0xff])];
						   
						   if(_this.nfcActType=='check'){
							   arr = [0x60, _this.nfcActType=='read'?0x09:0x0b,...bbbbb,0xff, 0xff,0xff, 0xff, 0xff, 0xff]
						   }
							let writeBuffer = new Uint8Array(arr).buffer;
							_this.NFCType.transceive({
								data: writeBuffer,
								success: function(res) {
									var arrayBuffer = new Uint8Array(res.data);
									var block = _this.ab2hex(arrayBuffer);
									console.log('数据认证成功', block)
									console.log("解密成功, 接收数据如下:", res);
									_this.nfcStatus = '1'
								},
								fail: function(err) {
									// _this.cloaseNfc();
									console.log("解密失败", err);
									_this.nfcStatus = '2'
								},
							});
					   },
					   fail(err) {
						   // _this.cloaseNfc();
						console.log(`NfcA.connect fail: ${JSON.stringify(err)}`)
					   }
				   });
					this.NFCType.isConnected({
						success: function (isConnected) {
							console.log('成功连接', isConnected);
							// 开始读
							if(_this.nfcActType=='read'){
								let readData = [0x30, 0x09]
								_this.NFCType.transceive({
									data:new Uint8Array(readData).buffer,
									success:function(res){
										// _this.cloaseNfc();
										var block_info_tmp='';
										var block_tmp = new Uint8Array(res.data);
										for (var j = 0; j < block_tmp.length; j++) {
										  var tmp = block_tmp[j].toString(16);
										  if (tmp.length < 2) {
											tmp = '0' + tmp;
										  }
										  if(j==block_tmp.length-1){
											block_info_tmp += tmp;
										  }else{
											block_info_tmp += tmp + ":";
										  }
										}
										if(_this.nfcStatusEncode=='encode'){//要加密
											_this.resultShow = true;
											_this.alertMsg='加密打卡成功'
											// uni.showToast({
											//   title: '加密打卡成功',
											//   duration: 2000
											// })
										}else if(_this.nfcStatusEncode=='decode'){
											_this.resultShow = true;
											_this.alertMsg='还原打卡成功'
											// uni.showToast({
											//   title: '还原打卡成功',
											//   duration: 2000
											// })
										}
										console.log('第12块读取数据返回HEX',block_info_tmp);
									},
									fail: function(err) {
										// _this.cloaseNfc();
										if(_this.nfcStatusEncode=='encode'){//加密
											_this.resultShow = true;
											_this.alertMsg='加密打卡失败'
											// uni.showToast({
											//   title: '加密打卡失败',
											//   duration: 2000
											// })
										}else if(_this.nfcStatusEncode=='decode'){
											_this.resultShow = true;
											_this.alertMsg='还原打卡失败'
											// uni.showToast({
											//   title: '还原打卡失败',
											//   duration: 2000
											// })
										}
										console.log("读取失败", err);
									}
								});
							}else if(_this.nfcActType == 'edit'){
								let editData = _this.nfcStatusEncode=='encode'
										?[0xa0,0x0b,0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0xff, 0x07, 0x80, 0x69, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b]
										:[0xa0,0x0b,0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x80, 0x69, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
								_this.NFCType.transceive({
									data: new Uint8Array(editData).buffer,
									success:function(res){
										// _this.cloaseNfc();
										if(_this.nfcStatusEncode=='encode'){//要加密
											_this.resultShow = true;
											_this.alertMsg='加密成功'
											// uni.showToast({
											//   title: '加密成功',
											//   duration: 2000
											// })
											_this.nfcStatus = '2'
										}else{
											_this.resultShow = true;
											_this.alertMsg='还原成功'
											// uni.showToast({
											//   title: '还原成功',
											//   duration: 2000
											// })
											_this.nfcStatus = '1'
										}
										console.log("写入成功, 接收数据如下:",res);
									},
									fail: function(err) {
										// _this.cloaseNfc();
										if(_this.nfcStatusEncode=='encode'){//要加密
											_this.resultShow = true;
											_this.alertMsg='加密失败'
											// uni.showToast({
											//   title: '加密失败',
											//   duration: 2000
											// })
										}else if(_this.nfcStatusEncode=='decode'){
											_this.resultShow = true;
											_this.alertMsg='还原失败'
											// uni.showToast({
											//   title: '还原失败',
											//   duration: 2000
											// })
										}
									}
								})
							}
						}
					})
				}
				// this.nfcActions({
				// 	cmd:0x60,
				// 	block:0x03,
				// 	cardId:cId.split(',').map(item=>'0x'+item),
				// 	key: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
				// })
			  }catch(e){}
			},
			changeType(buffer){
			 return Array.prototype.map.call(new Uint8Array(buffer),x => ('00'+x.toString(16)).slice(-2)).join(',')
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			uintToString(uintArray) {
			    var encodedString = String.fromCharCode.apply(null, uintArray),
			        decodedString = decodeURIComponent(escape(encodedString));
			    return decodedString;
			},
			// 将字节数组转换为字符串  
			byteArrayToHexString(inarray) {
				let i, j, inn;
				let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
				let out = "";
		
				for (j = 0; j < inarray.length; ++j) {
					inn = inarray[j] & 0xff;
					i = (inn >>> 4) & 0x0f;
					out += hex[i];
					i = inn & 0x0f;
					out += hex[i];
				}
				return out;
			},
			// 字符串转进制拼接 例：instr='ffffffffffffffff'
			HexStringToByteArray (instr) {
				var hexA = new Array();
				var pos = 0;
				var len = instr.length/2;
				for(var i=0; i<len; i++)
				{
					var s = instr.substr(pos, 2);
					var v = parseInt(s, 16);
					if(v>=128)
						v=v-256;
					hexA.push(v);
					pos += 2;
				}
				return hexA;
			},
		}
	}
</script>

<style scoped>
	.box{
		padding: 12px;
		padding-bottom: 60px;
		background-color: #fff;
	}
	page,.showDom{
		width: 100%;
		height: 100%;
		background-color: #fff;
	}
	.result{
		width: 100%;
		height: 100%;
		display: flex;
		position: absolute;
		left: 0;
		top: 0;
		background-color: #fff;
		align-items: center;
		justify-content: center;
	}
	.msgBox{
		animation:zoomD 0.9s linear infinite;
		font-size: 16px;
	}
	@keyframes zoomD{
		from{
			transform: scale(1);
		}
		50%{
			transform: scale(1.2);
		}
		to{
			transform: scale(1);
		}
	}
	.detailForm{
		width: 100%;
		height: 100%;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0px 0px 5px rgba(0,0,0,.1);
		padding: 20px;
		font-size: 13px;
		line-height: 38px;
	}
	.btns{
		display: flex;
		align-items: center;
		justify-content: center;
		height: 52px;
		margin-top: 30px;
	}
	.blueBtn{
		padding: 0 22px;
		border-radius: 4px;
		line-height: 30px;
		display: inline-block;
		color: #fff;
		font-size: 14px;
		background-color: #0081FF;
	}
	.selectBox{
		width: 160px;
		max-height: 150px;
		overflow: auto;
		border-radius: 4px;
		box-shadow: 0 0 5px rgba(0,0,0,.1);
		background: #fff;
		position: absolute;
		z-index: 222;
		top: 43px;
		left: 60px;
	}
	.selectItem{
		border-bottom: 1px solid rgba(0,0,0,.02);
		line-height: 30px;
		padding-left: 12px;
	}
	.detailLabel{
		width: 60px;
		color: #000000;
	}
	.detailInput{
		width: calc(100% - 60px);
		height: 38px;
		color: #555;
		font-size: 12px;
	}
	textarea.detailInput{
		height: 80px;
		line-height: 20px;
		border: 1px solid rgba(0,0,0,.1);
		border-radius: 2px;
		margin-top: 6px;
		padding: 6px;
	}
	.detailItem{
		border-bottom: 1px solid rgba(0,0,0,.04);
		display: flex;
		position: relative;
	}
	.waitCheck,.box{
		width:100%;
		height: 100%;
	}
	.waitCheck{
		display: flex;
		align-items: flex-start;
		justify-content: center;
		align-content: flex-start;
		flex-wrap: wrap;
		position: relative;
		background-color: #fff;
		border-radius: 8px;
	}
	.actItem{
		display: flex;
		align-items: center;
		margin-top: 20px;
	}
	.actItem .label{
		width: 100px;
		flex-shrink: 0;
		padding-bottom: 10px;
		font-size: 14px;
		/* border-bottom: 1px solid #d5d5d5; */
	}
	.warnTbn{
		background-color: rgba(19, 202, 156, 1);
		padding: 0 12px;
		color: white;
		font-size: 14px;
		font-weight: normal;
		flex-grow: 1;
		border-radius: 2px;
		height: 36px;
		line-height: 36px;
		text-align: center;
	}
	.uttonzs{
		background-color: rgba(19, 202, 156, 1);
		box-shadow: 0 10px 16px -6px rgba(19, 202, 156, 0.44);
		padding: 0 12px;
		color: white;
		font-size: 15px;
		font-weight: bold;
		width: calc(100% - 24px);
		border-radius: 6px;
		height: 44px;
		line-height: 44px;
		text-align: center;
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 20px;
	}
	.beforeSpeBox{
		width: 100vw;
		height: 90vh;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
	}
	.beforeSpe{
		height: 20px;
		background-color: #0081FF;
		border-radius: 6px;
		animation:fullWidth 3s linear infinite;
		margin-bottom: 12px;
	}
	@keyframes fullWidth{
		from{
			width:0px
		}
		to{
			width: 200px;
		}
	}
</style>
